<template>
	<m-layout class="card" :goBack="false">
		<m-text slot="back" ftsize="34" bold > 购物车</m-text>
		<template  slot="right">
			<m-icon type="icon-bianji1" @click="isEditor = !isEditor;" wh="38" color="var(--theme)"></m-icon>
			<!-- <m-text spa='0 0 0 10'>{{isEditor?'退出编辑':'编辑'}}</m-text> -->
		</template>
		<view class="card-head" slot="header"
			v-show="Number(userinfo.uLevel) > 0  ||  Number(userinfo.storeManager) > 0 ">
			<m-tabs class="m-tabs" v-model="tabIdx" lineHeight="5rpx" height="60rpx" fontSize="30rpx" :tabs="tabList"
				color="#333" activeColor="var(--theme)" pillsColor="var(--theme)" lineColor="var(--theme)"
				pillsBorderRadius="3rpx" @change="reset" />
		</view>
		<template v-for="(item, index) in cartList">
			<m-block class="li" spa=" 0 0 16" :key="index">
				<uni-swipe-action-item :key="item.id" @click="(res)=>{Delete(res,item)}" :right-options="options">
					<m-block class="li" gap="30">
						<!-- <view class="shopname flex" @click="Jump('/pages/home/goodsShop/goodsShop?sid=' + item.sid)">
					<m-icon type="icon-dianpu1" wh="32" spa="0 16 0 0"></m-icon>
					<text>{{item.shopname}}</text>
					<m-icon type="icon-xiala" wh="32" rotate="270" spa="0 16 0 0"></m-icon>
				</view> -->
						<view class="goods-box flex-between" @click="check(item)">
							<m-icon wh="40" spa="0 15 0 0" :color="item.checked?'#FA2B47':'#C5C5C5'"
								:type="item.checked?'icon-xuanzhong_-01':'icon-weixuanzhong_-01-01'"></m-icon>
							<view class="goods flex-between">
								<view class="left">
									<m-image radius="10" wh="136" types="goods" :src="item.picurl"></m-image>
								</view>
								<view class="center flex-column flex-between">
									<view class="title otp2">
										{{item.goodsname}}
									</view>
									<view class="Specification otp2">
										<text>{{item.attrname || item.sketch}}</text>
									</view>
									<view class="tag flex">
										<template v-for="(tItem,idx2) in item.goodsTagList">
											<text :key="idx2">{{tItem.tagValue}}</text>
										</template>
									</view>
								</view>
							</view>
						</view>
						<view class="price-box flex-between ">
							<view class="price flex">
								<m-number leftText="单价：" :value="item.price" :cny="item.coinid == 1"
									unit="积分"></m-number>
							</view>
							<view class="amount">
								<uni-number-box v-model="item.buycount" :min="1" :max="item.stock"
									@change=" e => { addCard(e, item)} " />
							</view>
						</view>
					</m-block>
				</uni-swipe-action-item>
			</m-block>

		</template>
		<template v-if="cartList.length <= 0 && !isLoading">
			<view>
				<m-block bgColor="unset" className="emptyCart" radius="0">
					<view class="top flex-column flex-center">
						<m-empty wh="310" gap="38 0 50 0" title='空空如也'></m-empty>
					</view>
				</m-block>
			</view>
		</template>
		<!-- 全选 -->
		<view class="bottom_all flex-between">
			<view class="left flex">
				<view class="flex-center" @click="checkAll">
					<m-icon wh="30" spa="0 16 0 0"
						:color="(allCheck.length > 0 && allCheck.length == cartList.length)?'#FA2B47':'#C5C5C5'"
						:type="(allCheck.length > 0 && allCheck.length == cartList.length)?'icon-xuanzhong_-01':'icon-weixuanzhong_-01-01'"></m-icon>
					<text>全选</text>
				</view>
			</view>
			<view class="right flex">
				<view class="total" v-if="!isEditor">
					<view>
						<text>已选{{totalPrice[0]}}件</text>
					</view>
					<view class="flex">
						<m-number leftText="合计：￥" :value="totalPrice[1]" color="#333333"></m-number>
					</view>
				</view>

				<template v-if="!isEditor">
					<m-button class="small" @click="submit" radius="15">结算</m-button>
				</template>
				<template v-else>
					<m-button @click="isShow = true" className="small resetBtn" radius="15">清空</m-button>
					<m-button @click="deleteGoods(0)" :loading="deleteLoading" radius="15" className="small"
						style="margin-left: 20rpx">删除</m-button>
				</template>
			</view>
		</view>
		<!-- 删除弹窗 -->
		<m-dialog v-model="isShow" :showCancel="true" cancelText="取消" confirmText="删除全部" @handleCancel="isShow = false"
			@handleConfirm="deleteGoods(1)">
			<view class="dialog-box">确定删除全部吗？</view>
		</m-dialog>
	</m-layout>
</template>

<script>
	import { GetShopCar, ShopCar_Del, ShopCar_Edit, GoodsFirst } from '@/api/Goods.js'
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				cartList: [],
				pageIndex: 1,
				pageCount: 1,


				tabIdx: 2,
				tabList: {
					1: '积分商城',
					3: '专属商城',
					4: '工具商城',
				},
				isShow: false,
				cartNo: '', // 购物车编号
				allChecked: false, //全选状态  true|false
				isEditor: false,
				isLoading: false,



				deleteLoading: false,
				deleteAllLoading: false,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}]
			};
		},
		onShow() {
			this.reset();
			this.isEditor = false;
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
			}),
			//全选
			allCheck() {
				const a = this.cartList.filter(item => {
					return item.checked == true;
				})
				return a || []
			},
			//计算总价  和 总量
			totalPrice() {
				let amount = 0,
					tPrice = 0;
				this.cartList.forEach(item => {
					if (item.checked) {
						tPrice += item.price * item.buycount;
						amount += 1;
					}
				})
				return [amount, tPrice]
			},
		},
		watch: {
			//监听编辑  切换时全为 false
			isEditor(val) {
				this.cartList.forEach(item => {
					item.checked = false;
				})
			},
		},
		methods: {
			reset() {
				this.pageCount = 1;
				this.pageIndex = 1;
				this.listArr = [];
				this.cartList = [];
				this.GetShopCar();

			},
			async GetShopCar() {
				this.isLoading = true;
				const { success, list, pageCount } = await GetShopCar({
					wards: 1,
					pageIndex: this.pageIndex,
				});
				this.isLoading = false;
				this.pageCount = pageCount;
				if (!success) return
				if (this.pageIndex <= 1) {
					this.cartList = list;
				} else {
					this.cartList = [...this.cartList, ...list];
				}
				this.pageIndex++;
				uni.stopPullDownRefresh();
			},
			checkAll() {
				const a = this.allCheck.length == this.cartList.length;
				//先获取状态  再给全选赋值
				this.cartList.forEach(item => {
					item.checked = !a;
				})
			},
			//选中状态处理
			check(item) {
				// this.cartList.forEach(item => {
				// 	item.checked = false;
				// })
				item.checked = !item.checked;
			},
			async addCard(e, item) {
				console.log('item===>', item)
				let data = {
					carid: item.id,
					count: e,
				};
				const res = await ShopCar_Edit(data);
				if (!res.success) {
					this.Toast(res.msg)
					item.count = item.count - 1;
				}
			},

			// 商品详情
			async GoodsFirst(id) {
				const { data, success } = await GoodsFirst({
					id: id
				});
				return Promise.resolve(data)
			},
			// 结算
			async submit() {
				let idx = this.allCheck.map(item => {
					item.gid = item.gid
					item.unitid = item.unitId
					item.unitName = item.unitDes
					if (item.checked) {
						return item
					}
				}, []);
				if (idx.length <= 0) {
					return this.Toast('请选择您要购买的商品')
				}
				console.log(idx)
				this.$store.commit('goods/SET_PAYGOODS', idx);
				this.Jump('/pagesA/order/sureOrder/sureOrder?isCard=1');
			},

			// // 多商品结算
			// async submit1() {
			// 	let idx = this.allCheck.map(item => {
			// 		if (item.checked) {
			// 			return item
			// 		}
			// 	}, []);
			// 	// const goods = {
			// 	// 	buycount: idx.buycount
			// 	// };

			// 	this.$store.commit('goods/SET_PAYGOODS', [goods]);
			// 	this.Jump('/shopping/sureOrder/sureOrder');
			// },
			// 批量删除购物车商品
			async deleteGoods(type = 1) {
				let a = [];
				let Arr = [];

				if (type == 0) {
					this.deleteLoading = true;
					Arr = this.allCheck;
				} else {
					this.deleteAllLoading = true;
					Arr = this.cartList
				}
				a = Arr.map(item => {
					return item.id.toString()
				}, [])

				let { success, msg } = await ShopCar_Del({carid:a});
				this.deleteAllLoading = false;
				this.deleteLoading = false;
				this.isShow = false;
				this.Toast(msg)
				this.reset();
			},
			async Delete(res, item) {
				uni.showLoading();
				let { success, msg } = await ShopCar_Del({carid:[item.id.toString()]});
				uni.hideLoading();
				this.Toast(msg)
				this.reset();
			},
		},




		onReachBottom() {
			this.GetShopCar();
			console.log("触底了");
			if (this.cartList.length <= 0) {
				this.$refs.hot.getData();
			}
		},
	}
</script>

<style lang="scss" scoped>
	.card-head {
		/deep/ .m-tabs {
			.v-tabs__container {
				display: flex;
				justify-content: space-around;
			}
		}
	}

	.card {
		position: relative;
		padding-bottom: var(--window-bottom);

		.top-left {
			font-size: 34rpx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #333333;
		}

		.top-right {
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #333333;
		}

		.li {
			.shopname {
				padding-bottom: 20rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.goods-box {
				.goods {
					flex: 1;
					align-items: flex-start;

					.center {
						padding-left: 20rpx;
						flex: 1;

						&>view {
							width: 100%;
							margin-bottom: 15rpx;
						}

						&>view:last-child {
							padding-bottom: 0;
						}

						.title {
							font-size: 26rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #333333;
						}

						.Specification {
							font-size: 22rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #999999;
							width: 100%;
						}

						.tag {
							overflow: hidden;

							text {
								display: inline-block;
								font-size: 20rpx;
								font-family: PingFang SC-Regular, PingFang SC;
								font-weight: 400;
								color: #FA2B47;
								border: 1px solid #FA2B47;
								border-radius: 4rpx;
								padding: 0rpx 6rpx;
								margin: 0 12rpx 0 0;
							}
						}
					}

				}
			}

			.price-box {
				.price {
					margin-right: 140rpx;
				}

				/deep/ .uni-numbox {
					border: 2rpx solid #EEEEEE;
					border-radius: 20rpx;
					padding: 0 10rpx;

					&>view {
						background: none !important;
						padding-bottom: 4rpx;
					}

					.uni-numbox__value {
						background: none !important;
						border-left: 2rpx solid #EEEEEE;
						border-right: 2rpx solid #EEEEEE;

						font-size: 24rpx;
						font-family: PingFang SC;
						font-weight: bold;
						color: #333333;
					}
				}
			}
		}
	}

	.bottom_all {
		width: 100%;
		box-sizing: border-box;
		position: fixed;
		z-index: 9;
		bottom: var(--window-bottom);
		left: 0;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
		background-color: #fdfdfd;
		border-top: 2rpx solid #F8F8F8;

		.left {}

		.total {
			padding-right: 30rpx;
			text-align: right;

			view:nth-of-type(1) {
				font-size: 22rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
			}

			view:nth-of-type(2) {
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}

		}


	}

	// 缺省页
	.emptyCart {
		.top {
			background-color: #ffffff;

			.emptyBt {
				margin: 41rpx 0 49rpx 0;
				display: inline-block;
				padding: 17rpx 102rpx;
				border-color: #FA2B47;
				color: #FA2B47;
			}
		}

		.goods-list {
			.title {
				text-align: center;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.list-box {
				display: grid;
				grid-template-columns: 1fr 1fr;
				grid-row-gap: 16rpx;
				grid-gap: 27rpx;
				padding-top: 20rpx;

				.li:nth-of-type(1n+2) {}
			}
		}
	}

	.pop_txt {
		font-size: 28rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #222222;
		text-align: center;
		margin-top: 48rpx;
		margin-bottom: 66rpx;
	}

	.resetBtn {
		border: none;
		background: #f4bf40 !important;
	}
</style>